﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp6
{
    public class ChunkManager
    {
        public ChunkDBConfig Config { get; private set; }
        private readonly List<Chunk> _chunks = new List<Chunk>();
        private long _nextOffset;

        public ChunkManager(ChunkDBConfig config)
        {
            Config = config;
            _nextOffset = 0;
        }
        public void Load()
        {
            if (!Directory.Exists(Config.StorePath))
            {
                Directory.CreateDirectory(Config.StorePath);
            }
            var existingChunkFiles = Directory.GetFiles(Config.StorePath, "*.log");
            foreach (var filePath in existingChunkFiles)
            {
                var chunk = new Chunk(filePath, Config);
                _chunks.Add(chunk);
            }
            FindLatestWritePosition();
        }

        private void FindLatestWritePosition()
        {
            _chunks.Sort((c1, c2) => c2.StartOffset.CompareTo(c1.StartOffset));
            var _currentOffset = _chunks.FirstOrDefault()?.StartOffset ?? 0;
            _nextOffset = _currentOffset + Config.DefaultChunkSize;
        }

        public Chunk GetCurrentChunk()
        {
            var lastChunk = _chunks.LastOrDefault();
            if (lastChunk == null)
            {
                throw new InvalidOperationException("Requested chunk for current, which is not present in ChunkManager.");
            }
            return lastChunk;
        }

        public Chunk CreateNewChunk()
        {
            var newChunkStartOffset = _nextOffset;
            var fileName = Config.FileNameStrategy.GenerateFileName(newChunkStartOffset);
            //var newChunk = new Chunk(fileName, newChunkStartOffset, Config.DefaultChunkSize, 20, 4096, 8092);
            var newChunk = Chunk.InitNew(Path.Combine(Config.StorePath, fileName), Config);
            _chunks.Add(newChunk);
            _nextOffset = newChunkStartOffset + Config.DefaultChunkSize;
            return newChunk;
        }

    }
}
